package com.lagou.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

@Component
public class ConnectionUtils {

    @Autowired
    private DataSource dataSource;

    private ThreadLocal<Connection> threadLocal = new ThreadLocal<>();

    /*从数据源中获取一个连接对象*/
    public Connection getConnection() {
        try {
            return dataSource.getConnection();//从数据源中获取一个连接对象
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 从当前线程获取连接
     */
    public Connection getCurrentThreadConnection() throws SQLException {
        /**
         * 判断当前线程中是否已经绑定连接，如果没有绑定，需要从连接池获取一个连接绑定到当前线程
         */
        Connection connection = threadLocal.get();
        if (connection == null) {
            // 从连接池拿连接并绑定到线程
            connection = getConnection();
            // 绑定到当前线程
            threadLocal.set(connection);
        }
        return connection;
    }

    //释放本地线程上的连接对象
    public void release(){
        threadLocal.remove();
    }
}
